package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    private static String FILE_UPLOAD_PATH = "D:\\learn\\Java Project\\CangQiong Takeaway\\sky-take-out\\sky-server\\src\\main\\resources\\upload\\";

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);
        File dir = new File(FILE_UPLOAD_PATH);
        if (!dir.exists() || !dir.isDirectory()) {
            boolean created = dir.mkdirs();
            if(created) {
                log.info("创建文件夹成功: {}", FILE_UPLOAD_PATH);
            } else {
                log.warn("创建文件夹失败或已经存在: {}", FILE_UPLOAD_PATH);
            }
        }
        try{
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName =UUID.randomUUID().toString() + extension;

            Path targetLocation = Paths.get(FILE_UPLOAD_PATH).resolve(objectName).normalize();
            try {
                Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
                log.info("文件上传成功: {}", objectName);
            } catch (IOException e) {
                log.error("文件上传失败: {}", objectName, e);
                return Result.error(MessageConstant.UPLOAD_FAILED);
            }
            //文件请求路径
            String finalUrl = "http://localhost:8080/static/" + objectName;
            return  Result.success(finalUrl);
        }catch (Exception e){
            log.error("文件上传失败: {}", e);
        }
            return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
